<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-25
 * Time: 下午7:24
 */

namespace home\models;


use common\models\db\User;
use yii\base\Model;

class FormEmailActiveLinkResend extends Model
{
    public $email;
    public $code;

    public function attributeLabels()
    {
        return [
            'email' => "邮箱",
            'code' => "验证码",
        ];
    }

    public function rules()
    {
        return [
            ['email', 'trim'],
            [['email', 'code'], 'required'],
            ['email', 'email'],
            ['email', 'exist', 'targetClass' => User::class, 'targetAttribute' => 'email'],
            ['code', 'captcha'],
        ];
    }

    public function send()
    {
        $user = User::findOne(['email' => $this->email]);
        if (!$user){
            \Yii::$app->session->setFlash("error", "没有这个邮箱的账户，请注册！");
            return \Yii::$app->controller->redirect(['site/signup']);
        }
        if ($user->status == $user::STATUS_ACTIVE){
            \Yii::$app->session->setFlash('info', "你的账号已经激活了！请登录。");
            return \Yii::$app->controller->redirect(['site/login']);
        }
        $code = $user->generateCode();
        $link = \Yii::$app->urlManager->createAbsoluteUrl(['site/active-email', 'email'=>$this->email, 'code'=>$code]);
        $html = \Yii::$app->controller->renderPartial('/emails/signup', ['link' => $link]);
        $bool = \Yii::$app->mailer->compose()->setTo($this->email)->setSubject("账号激活链接")->setHtmlBody($html)->send();
        if ($bool){
            \Yii::$app->session->setFlash('success', "发送成功，请去邮箱激活账号。");
            return \Yii::$app->controller->redirect(['site/login']);
        }else{
            \Yii::$app->session->setFlash('error', "发送邮件失败！");
            return \Yii::$app->controller->redirect(['site/resend-active-link-for-email']);
        }
    }
}